package engine;

import java.awt.Graphics2D;
import java.awt.Polygon;

/**
 * 
 * A triangle in 2D space, represented by three vectors. Used for collision
 * detection in abstract polygons.
 * 
 * @author dylan
 *
 */
public class Triangle {
	Vector p1, p2, p3;	//Vertices
	Vector normal1, normal2, normal3;	//Normal vectors
	
	Line side1, side2, side3;	//Sides
	
	public Triangle(Vector p1, Vector p2, Vector p3){
		this.p1 = p1;
		this.p2 = p2;//.subtract(p1);
		this.p3 = p3;//.subtract(p1);
		
		side1 = new Line(p1, p2);
		side2 = new Line(p2, p3);
		side3 = new Line(p3, p1);
		
		/*
		 * Generate normal vectors.
		 */
		normal1 = new Vector(-side1.a, -side1.b);
		normal2 = new Vector(-side2.a, -side2.b);
		normal3 = new Vector(-side3.a, -side3.b);
		
	}
	
	
	/**
	 * 
	 * Returns null if the specified point is not within the triangle. Else, returns
	 * the shortest path for the point to exit the triangle.
	 * polygon.addPoint((int) p1.getX(), (int) p1.getY());
	 * @param v
	 * @return
	 */
	public Vector pointInTriangle(Vector v){
		
		double dist1 = side1.distanceToLine(v);
		double dist2 = side2.distanceToLine(v);
		double dist3 = side3.distanceToLine(v);
		
		if (dist1 >= 0 && dist2 >= 0 && dist3 >= 0){
			System.out.println("(" + dist1 + ", " + dist2 + ", " + dist3 + ")");
			if (dist1 <= dist2 && dist1 <= dist3){
				return normal1.scale(dist1);
			} else if (dist2 <= dist3 && dist2 <= dist1){
				return normal2.scale(dist2);
			} else {
				return normal3.scale(dist3);
			}
		} else {
			return null;
		}
	}
	
	/**
	 * 
	 * Draw the triangle to the graphics object.
	 * 
	 * @param g
	 */
	public void draw(Graphics2D g){
		Polygon polygon = new Polygon();
		polygon.addPoint((int) p1.getX(), (int) p1.getY());
		polygon.addPoint((int) p2.getX(), (int) p2.getY());
		polygon.addPoint((int) p3.getX(), (int) p3.getY());
		g.drawPolygon(polygon);
	}
}
